<template>
  <div>
    <div class="header">
      <div class="container">
        <div class="row white--text py-lg-5">
          <div class="col col-4">
            <div class="text-center">
              <count-to
                class="body-1 text-lg-h4 text-sm-h5"
                :start-val="0"
                :end-val="statistics.accountSum"
                separator=","
                autoplay
              />
              <div class="body-2 my-2">Users</div>
            </div>
          </div>
          <div class="col col-4">
            <div class="text-center">
              <count-to
                class="body-1 text-lg-h4 text-sm-h5"
                :start-val="0"
                :end-val="statistics.orderSum"
                separator=","
                autoplay
              />
              <div class="body-2 my-2">Orders</div>
            </div>
          </div>
          <div class="col col-4">
            <div class="text-center">
              <count-to
                class="body-1 text-lg-h4 text-sm-h5"
                :start-val="0"
                :end-val="statistics.userSum"
                separator=","
                autoplay
              />
              <div class="body-2 my-2">Accounts</div>
            </div>
          </div>
        </div>
        <v-row>
          <v-col sm="12" md="6" lg="4" xl="3" cols="12"
            v-for="item in productList"
            :key="item.id"
          >
            <v-card elevation="12" class="mx-auto rounded-xl overflow-hidden">
              <div class="img-box">
                 <v-img max-width="300" class="img" :src="netflix"/>
                 <div class="order-stat"> Sold {{item.soldNum}} </div>
              </div>
              <div class="d-flex">
                <v-card-title>{{ item.productName }}</v-card-title>
                <v-spacer></v-spacer>
                <v-card-title>
                  <span class="body-1 grey--text font-weight-bold">USD</span>
                  <span class="red--text text-h5 font-weight-bold mx-1">
                    {{item.saleDisplayPrice}}
                  </span>
                  <span class="subtitle-2 grey--text">
                    <span span class="origin-price body-1">
                      {{item.saleDisplayOriPrice}}
                    </span>/month
                  </span>
                  <v-chip color="red lighten-1"
                   outlined label small>{{item.saleDiscounts || 'SALE'}}</v-chip>
                </v-card-title>
              </div>
              <v-card-text>
                <v-divider></v-divider>
                <div class="my-2">
                  <div v-for="desc in item.desc" :key="desc" class="d-flex align-center">
                    <v-icon class="ma-2" notranslate color="green">mdi-check</v-icon>
                    <span class="font-weight-black">· {{ desc }}</span>
                  </div>
                </div>
              </v-card-text>
              <v-card-actions>
                <!-- <v-btn block rounded dark large color="red lighten-1"
                  target="_blank"
                  tag="a"
                  :href="item.buyNowLink">BUY NOW</v-btn> -->
                <v-btn block rounded dark large color="red lighten-1"
                  @click="handleShowBuy(item)">BUY NOW</v-btn>
              </v-card-actions>
            </v-card>
            <v-spacer></v-spacer>
          </v-col>
        </v-row>
      </div>
    </div>
    <div class="container">
      <div class="mt-5">
        <v-card color="grey lighten-4" flat>
          <v-row>
            <v-col sm="12" md="6" lg="4" cols="12"
            v-for="car in carList"
            :key="car.carId"
            >
              <v-card flat outlined rounded="lg">
                <div class="car">
                  <van-card
                    class="pa-5"
                    num="1"
                    currency="USD"
                    :price="car.price[0]"
                    :title="car.cardName"
                    :thumb="nfImg"
                    :origin-price="car.price[1]">
                      <template #tags>
                        <van-tag
                          v-for="saleInfo in car.saleInfo"
                          :key="saleInfo"
                          style="background-color: rgb(255, 82, 82)"
                          size="medium"
                          class="mr-1">{{ saleInfo }}</van-tag>
                      </template>
                      <template #bottom>
                        <div>
                          <van-tag plain type="danger" size="medium">
                            {{ car.cardSaleDiscount }}
                          </van-tag>
                        </div>
                      </template>
                  </van-card>
                  <van-grid :border="false" :column-num="5" style="cursor: pointer;">
                    <template v-for="item in car.carSeatDetailList">
                      <van-grid-item
                        v-if="item.seatStatus===0"
                       :key="item.seatNo"
                        class="grid-item"
                        @click="handleToBuyLink(car, item)">
                        <van-badge :content="item.seatNo">
                          <v-img width="50" height="50" class="img" :src="imgSrc"/>
                        </van-badge>
                        <div class="text-caption grey--text mt-2
                         mb-2 text-ellipsis"> BUY NOW </div>
                      </van-grid-item>
                      <van-grid-item
                        v-if="item.seatStatus===1"
                        class="grid-item"
                        :key="item.seatNo"
                        @click="handleClickSeal">
                        <van-badge :content="item.seatNo">
                        <v-img width="50" height="50" class="img" :src="avatars"/>
                      </van-badge>
                      <div class="text-caption grey--text mt-2
                       mb-2 text-ellipsis">
                        {{ item.passengerName && item.passengerName.length > 6 ?
                         item.passengerName.substring(0,6) + '...': item.passengerName }}
                      </div>
                      <div class="mt-6 time-ago"></div>
                      <!-- <div class="mt-6 time-ago red lighten-1">32 Days ago</div> -->
                      </van-grid-item>
                    </template>
                  </van-grid>
                </div>
              </v-card>
            </v-col>
          </v-row>
        </v-card>
        <div class="text-center py-5">
          <v-btn
          v-if="ismore" outlined dark
          color="red lighten-1"
          rounded width="150"
          @click="getMore">More</v-btn>
          <van-divider v-else > No More</van-divider>
        </div>
      </div>
    </div>
    <!--buy-->
    <buy :visible.sync="showBuy" :sku="currentSku" :params="buyParams"></buy>
  </div>
</template>

<script>
/* eslint-disable @typescript-eslint/no-var-requires */
import CountTo from 'vue-count-to';
import {
  Card, Tag, Grid, GridItem, Badge, Toast, Divider,
} from 'vant';
import Vue from 'vue';
import {
  getPortaProduct,
  getPortanfcar,
  getCountStatistic,
  getPortSkuList,
} from '@/api/home';
import { ERROR_OK } from '@/api/config';
import Buy from '../components/Buy/index.vue';

Vue.use(Card);
Vue.use(Tag);
Vue.use(Grid);
Vue.use(GridItem);
Vue.use(Badge);
Vue.use(Toast);
Vue.use(Divider);

const nfImg = require('@/assets/product/nf.jpg');
const imgSrc = require('@/assets/icon/emptyUser.png');
const netflix = require('@/assets/product/netflix.png');
const avatars = require('@/assets/icon/ava-1.png');

export default Vue.extend({
  components: { CountTo, Buy },
  data() {
    return {
      statistics: {
        accountSum: 0,
        orderSum: 0,
        userSum: 0,
      },
      productList: [],
      carList: [],
      tab: 'null',
      imgSrc,
      nfImg,
      netflix,
      avatars,
      pageCount: 12,
      pageNo: 1,
      totalCount: 0,
      showBuy: false,
      currentSku: {},
      buyParams: {},
    };
  },
  created() {
    this.getInitData();
  },
  computed: {
    ismore() {
      let ret = true;
      const currentNum = this.pageCount * this.pageNo;
      if (currentNum >= this.totalCount) {
        ret = false;
      }
      return ret;
    },
  },
  methods: {
    handleShowBuy(car) {
      const { id, selectableProductType } = car;
      getPortSkuList({
        categoryId: id,
        selectableProductType,
      }).then((res) => {
        if (res.code === ERROR_OK) {
          this.currentSku = this.formatterGoodSku(res.data);
          this.buyParams = { isRenewalBill: 0 };
          this.showBuy = true;
        }
      });
    },
    handleToBuyLink(car, item) {
      const { categoryId, selectableProductType } = car;
      const { carSeatId } = item;
      getPortSkuList({
        categoryId,
        selectableProductType,
      }).then((res) => {
        if (res.code === ERROR_OK) {
          this.currentSku = this.formatterGoodSku(res.data);
          this.buyParams = { isRenewalBill: 0, carSeatId };
          this.showBuy = true;
        }
      });
    },
    handleClickSeal() {
      Toast({
        message: 'Choose an available profile',
      });
    },
    getMore() {
      this.getNfCar();
    },
    getInitData() {
      getCountStatistic().then((res) => {
        if (res.code === ERROR_OK) {
          this.statistics = res.data;
        }
      });
      getPortaProduct().then((res) => {
        if (res.code === ERROR_OK) {
          const productList = res.data || [];
          this.productList = productList.map((item) => {
            const { productDescription = '' } = item;
            return { ...item, desc: productDescription.split('|') };
          });
        }
      });
      getPortanfcar({
        pageCount: this.pageCount,
        pageNo: this.pageNo,
      }).then((res) => {
        if (res.code === ERROR_OK) {
          const { pageList = [], totalCount } = res.data;
          this.carList = this.formatCar(pageList);
          this.totalCount = totalCount;
        }
      });
    },
    getNfCar() {
      this.pageNo += 1;
      const params = {
        pageCount: this.pageCount,
        pageNo: this.pageNo,
      };
      getPortanfcar(params).then((res) => {
        if (res.code === ERROR_OK) {
          const { pageList = [], totalCount } = res.data;
          this.carList = this.carList.concat(this.formatCar(pageList));
          this.totalCount = totalCount;
        }
      });
    },
    formatCar(data) {
      return data.map((item) => {
        const { cardSaleInfo = '', cardSalePrice } = item;
        const price = cardSalePrice.split('-');
        return { ...item, price, saleInfo: cardSaleInfo.split('|') };
      });
    },
    formatterGoodSku(data) {
      const { monthNumSet, screensSet, skuList } = data;
      const tree = [
        {
          k: 'Purchase months',
          k_id: '1',
          k_s: 'monthNum',
          v: monthNumSet.map((item) => ({
            id: item,
            name: `${item} months`,
          })),
        },
        {
          k: 'Select screen',
          k_id: '1',
          k_s: 'screens',
          v: screensSet.map((item) => ({
            id: item,
            name: `${item} screen`,
          })),
        },
      ];
      const list = skuList.map((item) => {
        const {
          screens, monthNum, originalPrice, id, actualPrice, discount,
        } = item;
        return {
          id,
          screens,
          monthNum,
          price: actualPrice,
          stock_num: 110,
          discount,
          originalPrice,
        };
      });
      return { tree, list };
    },
  },
});
</script>

<style scoped lang="scss">
  .header {
    background: linear-gradient(#ef5350,#1989fa);
  }
  .img-box {
    text-align: center;
    background: #000;
    padding: 20px 0 30px;
    max-height: 140px;
    overflow: hidden;
    position: relative;
  }
  .img {
    margin: 0 auto;
    width: 50%;
    max-width: 300px;
  }
  .order-stat {
    padding: 0 0 10px 15px;
    position: absolute;
    bottom: 0;
    left: 0;
    color: #ccc;
  }
  .origin-price{
    display: inline-block;
    margin-left: 5px;
    color: #969799;
    font-size: 10px;
    text-decoration: line-through;
  }
  .car {
    overflow: hidden;
  }
  .van-card__title {
    font-size: 16px;
    margin-bottom: 6px;
  }
  .time-ago {
    position: absolute;
    color: #fff;
    font-size: 10px;
    text-align: center;
    bottom: 0;
    left: 0;
    width: 100%;
    opacity: .6;
  }
  .grid-item {
    overflow: hidden;
  }
  .text-ellipsis {
    display: -webkit-box;
    overflow: hidden;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
  }
</style>
